package com.ktgj.hotel.service.impl;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ktgj.hotel.domain.dic.*;
import com.ktgj.hotel.domain.vo.*;
import com.ktgj.hotel.mapper.DicCountyMapper;
import com.ktgj.hotel.domain.rooms.FoodSurrounding;
import com.ktgj.hotel.utils.HotelUtils;
import com.ktgj.hotel.utils.Http;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.hotel.mapper.DicCityMapper;
import com.ktgj.hotel.service.IDicCityService;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-10-28
 */
@Service
public class DicCityServiceImpl implements IDicCityService 
{
    @Autowired
    private DicCityMapper dicCityMapper;

    @Autowired
    private DicCountyMapper dicCountyMapper;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public DicCity selectDicCityById(Long id)
    {
        return dicCityMapper.selectDicCityById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param dicCity 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<DicCity> selectDicCityList(DicCity dicCity)
    {
        return dicCityMapper.selectDicCityList(dicCity);
    }

    @Override
    public List<DicCity> queryDicCityList() {
        return dicCityMapper.queryDicCityList();
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param dicCity 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertDicCity(DicCity dicCity)
    {
        return dicCityMapper.insertDicCity(dicCity);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param dicCity 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateDicCity(DicCity dicCity)
    {
        return dicCityMapper.updateDicCity(dicCity);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteDicCityByIds(Long[] ids)
    {
        return dicCityMapper.deleteDicCityByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteDicCityById(Long id)
    {
        return dicCityMapper.deleteDicCityById(id);
    }

    /**
     * 查询全部市信息(远程)
     * */
    @Override
    public List<DicCityVo> selectAllDicCityList() {
        List<DicCity> dicCityList = dicCityMapper.selectAllDicCityList();
        List<DicCityVo> dicCityVoList = new ArrayList<>();

        for (DicCity dicCity : dicCityList) {
            DicCityVo dicCityVo = new DicCityVo();
            dicCityVo.setId(dicCity.getId());
            dicCityVo.setProvinceId(dicCity.getProvinceId());
            dicCityVo.setCityName(dicCity.getCityName());
            dicCityVoList.add(dicCityVo);
        }
        return dicCityVoList;
    }

    @Override
    public List<HotCity> queryHotCity() {
        return dicCityMapper.queryHotCity();
    }

    /**
     * 查询酒店周边-景点
     * @param request
     * @return
     */
    @Override
    public AttractionsSurrounding hotelAttractionsSurrounding(SurroundingRequest request) {
        AttractionsSurrounding attractionsSurrounding = new AttractionsSurrounding();
        SurroundingResponse response = new SurroundingResponse();
        try {
            response = (SurroundingResponse) selectSurrounding(response, request.getQuery(), request.getLocation());
            attractionsSurrounding.setStatus(response.getStatus());
            for (ResultInfo result : response.getResults()) {
                AttractionsResultInfo attractionsResultInfo = new AttractionsResultInfo();
                attractionsResultInfo.setName(result.getName());
                attractionsResultInfo.setOverall_rating(result.getDetail_info().getOverall_rating());
                attractionsResultInfo.setDistance(result.getDetail_info().getDistance());
                attractionsSurrounding.getResults().add(attractionsResultInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return attractionsSurrounding;
    }

    /**
     * 查询酒店周边-美食
     * @param request
     * @return
     */
    @Override
    public FoodSurrounding hotelFoodSurrounding(SurroundingRequest request) {
        FoodSurrounding foodSurrounding = new FoodSurrounding();
        SurroundingResponse response = new SurroundingResponse();
        try {
            response = (SurroundingResponse) selectSurrounding(response, request.getQuery(), request.getLocation());
            foodSurrounding.setStatus(response.getStatus());
            for (ResultInfo result : response.getResults()) {
                FoodResultInfo foodResultInfo = new FoodResultInfo();
                foodResultInfo.setName(result.getName());
                foodResultInfo.setOverall_rating(result.getDetail_info().getOverall_rating());
                foodResultInfo.setAddress(result.getAddress());
                foodResultInfo.setDistance(result.getDetail_info().getDistance());
                foodResultInfo.setDistance(result.getDetail_info().getDistance());
                foodSurrounding.getResults().add(foodResultInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return foodSurrounding;
    }

    /**
     * 查询酒店周边-交通
     * @param request
     * @return
     */
    @Override
    public TrafficSurrounding hotelTrafficSurrounding(SurroundingRequest request) {
        TrafficSurrounding trafficSurrounding = new TrafficSurrounding();
        SurroundingResponse response = new SurroundingResponse();
        try {
            response = (SurroundingResponse) selectSurrounding(response, request.getQuery(), request.getLocation());
            trafficSurrounding.setStatus(response.getStatus());
            for (ResultInfo result : response.getResults()) {
                TrafficResultInfo trafficResultInfo = new TrafficResultInfo();
                trafficResultInfo.setName(result.getName());
                trafficResultInfo.setDistance(result.getDetail_info().getDistance());
                trafficResultInfo.setTag(result.getDetail_info().getTag());
                if (request.getQuery().contains("飞机场")) {
                    if (result.getDetail_info().getTag().contains("飞机场"))
                        trafficSurrounding.getResults().add(trafficResultInfo);
                } else {
                    trafficSurrounding.getResults().add(trafficResultInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return trafficSurrounding;
    }

    /**
     * 城市列表
     * */
    @Override
    public List<popularCityVo> cityList() throws Exception {
        List<popularCityVo> popularCityVoList = new ArrayList<>();
        List<DicCity> dicCityList = dicCityMapper.popularCityList();//城市
        List<DicCounty> county = dicCountyMapper.county();//区县

        if (dicCityList != null && dicCityList.size() > 0 && county != null && county.size() > 0){
            for (DicCity dicCity : dicCityList) {//城市
                if (!dicCity.getCityName().equals("市辖区")){
                    popularCityVo popularCityVo = new popularCityVo();
                    String pinYinHeadChar = getPinYinHeadChar(dicCity.getCityName()).substring(0, 1);//城市首字母

                    popularCityVo.setPopularCityId(dicCity.getId());
                    popularCityVo.setPopularCityName(dicCity.getCityName());
                    popularCityVo.setPopularCityLetter(pinYinHeadChar);

                    if (dicCity.getIsHot().equals("1")){
                        popularCityVo.setPopular("true");
                    }
                    else {
                        popularCityVo.setPopular("false");
                    }
                    popularCityVoList.add(popularCityVo);
                }
            }
            for (DicCounty dicCounty : county) {//区县
                if (!dicCounty.getCountyName().equals("市辖区")){
                    popularCityVo popularCityVo = new popularCityVo();
                    String headChar = getPinYinHeadChar(dicCounty.getCountyName()).substring(0, 1);//城市首字母

                    popularCityVo.setPopularCityId(dicCounty.getId());
                    popularCityVo.setPopularCityName(dicCounty.getCountyName());
                    popularCityVo.setPopularCityLetter(headChar);
                    popularCityVoList.add(popularCityVo);
                }
            }
            return popularCityVoList;
        }
        else {
            throw new Exception("未查询到相关数据");
        }
    }

    /**
     * 城市列表(小程序)
     * */
    @Override
    public List<LetterVo> letterList() throws Exception {
        String[] letter = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
                "T", "U", "V", "W", "X", "Y", "Z"};

        List<LetterVo> letterVoList = new ArrayList<>();

        List<popularCityVo> popularCityVoList;
        try {
            popularCityVoList = cityList();
        } catch (Exception e){
            throw new Exception("程序出现异常");
        }

        if (popularCityVoList != null && popularCityVoList.size() > 0){
            for (String let : letter) {
                List<popularCityVo> popularCityVos = new ArrayList<>();
                for (popularCityVo popularCityVo : popularCityVoList) {
                    if (popularCityVo.getPopularCityLetter().equals(let)){
                        popularCityVos.add(popularCityVo);
                    }
                }
                LetterVo letterVo = new LetterVo();
                letterVo.setLetter(let);
                letterVo.setPopularCityVoList(popularCityVos);

                if (letterVo.getPopularCityVoList() != null && letterVo.getPopularCityVoList().size() > 0){
                    letterVoList.add(letterVo);
                }
            }
        }
        else {
            throw new Exception("未查询到相关数据");
        }

        return letterVoList;
    }

    /**
     * 城市名称查经纬度
     * */
    @Override
    public String dicCityLngAnfLat(String cityName) throws Exception {
        if (cityName != null && !cityName.equals("")){
            DicCity dicCity = dicCityMapper.dicCityLngAnfLat(cityName + "%");
            if (dicCity != null && dicCity.getGoogleLon() != 0 && dicCity.getGoogleLat() != 0){
                String lngAndLat = dicCity.getGoogleLon() + "," + dicCity.getGoogleLat();
                return lngAndLat;
            }
            else {
                return null;
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 获取城市名称
     * */
    @Override
    public DicCity selectCityName(Long id) {
        DicCity dicCity = dicCityMapper.selectCityName(id);
        return dicCity;
    }

    /**
     * 获取城市id
     * */
    @Override
    public Long selectCityId(String name) {
        if (name != null && !name.equals("")){
            name = name + "%";
        }
        DicCity dicCity = dicCityMapper.selectCityId(name);
        return dicCity.getId();
    }

    /**
     * 获取中文首字母
     * */
    public static String getPinYinHeadChar(String str) {
        StringBuilder convert = new StringBuilder();
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert.append(pinyinArray[0].charAt(0));
            } else {
                convert.append(word);
            }
        }
        String toUpperCase = convert.toString().toUpperCase();
        return toUpperCase;
    }

    private <T> T selectSurrounding(T response, T query, T location) {
        String responseData = "";
        String url = "";
        String encode = URLEncoder.encode(query.toString());
        try {
            url = HotelUtils.URI + "?query=" + encode;
            url += "&location=" + location;
            if (query.toString().contains("飞机场") || query.toString().contains("火车站")) {
                url += "&radius=200000&output=json&scope=2&coord_type=3";
            } else {
                url += "&radius=2000&output=json&scope=2&coord_type=3";
            }
            url += "&ak=" + HotelUtils.AK;
            responseData = Http.Send("GET", url, "");
            response = (T) JSON.parseObject(responseData, response.getClass());
            return response;
        } catch (Exception e) {
            return null;
        }
    }
}
